import { getMoreUserInfo, getUserInfo, login } from '@/api/user'
import { resetRouter } from '@/router'
import { getToken, setToken } from '@/utils/auth'
import { removeToken } from '@/utils/auth'

const state = () => ({
  token: getToken(),
  userInfo: {}
})

const mutations = {
  setToken(state, newToken) {
    state.token = newToken
  },
  setUserInfo(state, newUserInfo) {
    state.userInfo = newUserInfo
  }
}

const actions = {
  async getToken(context, data) {
    const token = await login(data)
    setToken(token)
    context.commit('setToken', token)
  },
  async getUserInfo(context) {
    const res = await getUserInfo()
    const moreRes = await getMoreUserInfo({ id: res.userId })
    // console.log(res)
    context.commit('setUserInfo', { ...res, ...moreRes })
  },
  isLogOut(context) {
    removeToken()
    context.commit('setToken', undefined)
    context.commit('setUserInfo', {})
    resetRouter()
    context.commit('permission/setRoutes', [], { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
